<?php

class Application_Model_Cart extends Application_Model_DomainObject{
	
	protected $_id;
	
	/**
	 * 购物车编号
	 */
	protected $_cartId;
	
	protected $_userId;
	
	protected $_dateCreated;
	
	protected $_items;
	
    public $_maxItemsCount = 30;
    
    protected $_shops;
    
    protected $_isSeleted;

    /**
	 * 返回当前购物车所有产品项
     * @return array 
	 */
	public function getItems(){
		if(null == $this->_items){			
			$this->_items = Application_Model_CartItem::getByCartId($this->Id);
		}
		return $this->_items;
	}
    
    /**
     * 购物车总额 
     */
    public function getTotal(){
        return $this->getProductTotal() + $this->getShipFeeTotal();
    }
    
    /**
     * 商品总额
     * @return type 
     */
    public function getProductTotal(){
        $sum=0;
        foreach ($this->getItems() as $item){
                $sum+= $item->SubTotal;
        }
        return $sum;
    }
    
    /**
     * 运费总额
     * @return type 
     */
    public function getShipFeeTotal(){
        $sum=0;
        foreach ($this->getShops() as $shop){
            $sum+= $this->getShopMaxShipFee($shop->Id);
        }
        return $sum;
    }
    
    /**
     * 因为一个店铺只收一次运费,所以按最大价格收一次运费
     * @param int $shopId
     * @return number 
     */
    private function getShopMaxShipFee($shopId){
        $shopItems = $this->getItemsByShopId($shopId);
        $fees = array();
        foreach ($shopItems as $item)
            array_push ($fees, $item->ShipFee);
        return max($fees);
    }

    /**
     * 返回当前购物车产品的所有店家
     * @return array 
     */
    public function getShops(){
        if (NULL != $this->_shops){
            return $this->_shops;
        }
        
        $this->_shops = array();
        $items = $this->getItems();
        $shopIds =  array();
        foreach ($items as $item){
            if(in_array($item->ShopId, $shopIds))
                continue;
            array_push($shopIds,$item->ShopId);
            array_push($this->_shops, $item->Shop);
        }
        return $this->_shops;
    }
    
    /**
     * 返回ShopID返回对应的购物车商品 
     * @return array
     */
    public function getItemsByShopId($shopId){
        $items = $this->getItems();
        
        $result = array();
        foreach ($items as $item){
            if ($item->ShopId == $shopId){
                array_push($result, $item);
            }
        }
        return $result;
    }

    /**
	 * 返回当前用户的购物车对象
     * @param bool $isOnlySelected 是否只显示选中的商品
	 * @return Application_Model_Cart
	 */
	public static function current($isSelected=TRUE){
        
		//从Cookie中获取当前购物车ID，如果Cookie没有记录，就设置当前SesionId到Cookie中
		$cartId = Zend_Session::getId();
		if(isset($_COOKIE[CART_ID]))
			$cartId = $_COOKIE[CART_ID];
		else 
			setcookie(CART_ID,$cartId,time()+365*24*3600);
		 
		$cart = Application_Model_Cart::getByCartId($cartId);
        
		if(null == $cart){
			$cart = new Application_Model_Cart();
			$cart->CartId = $cartId;
			$cart->UserId = Application_Model_User::current()->Id;
			$cart->DateCreated = date('Y-m-d H:i:s');
			$cart->save();
		}
        
        $cart->IsSeleted = $isSelected;
		return $cart;
	}
	
	/**
	 * 根据cartId返回一个cart对象
	 * @param string $cartId
	 * @return Application_Model_Cart
	 */
	public static function getByCartId($cartId){
		$db = new Application_Model_DbTable_Cart();
		return $db->getByCartId($cartId);
	}
	
	/**
	 * 根据UserID返回Cart对象
	 * @param int $userId
	 * @return Application_Model_Cart
	 */
	public static function getByUserId($userId){
		$db = new Application_Model_DbTable_Cart();
		return $db->getByUserId($userId);
	}
	
	/**
	 * 添加一个产品到购物车
	 * @param Application_Model_Product $product 产品
	 * @param int $quantity 数量
	 * @return Application_Model_CartItem
	 */
	public function addCartItem($product,$quantity ,$comment=''){
		$this->_items = null;		
		//遍历现有的购物车，如果已经有相同的产品，则数量相加，并直接返回此产品
		foreach($this->getItems() as $item){
			if($item->ProductId == $product->Id){
				$item->quantity += $quantity;
                if($comment=='填写商品备注')
                    $comment='';
				$item->comment .= $comment;
				$item->save();				
				return $item;
			}
		}
		
		//如果此产品还未添加，则新增到购物车
		$cartItem = new Application_Model_CartItem();
		$cartItem->CartId = $this->Id;
		$cartItem->ProductName = $product->Name;
		$cartItem->quantity = $quantity;
		$cartItem->ProductId = $product->Id;
		$cartItem->DateCreated = date('Y-m-d H:i:s');
		$cartItem->Comment = $comment;
		$cartItem->Price = $product->Price;
		$cartItem->ShipFee = $product->ShipFee;
        $cartItem->ShopId = $product->ShopId;
        $cartItem->SkuNo = $product->Sku;
        $cartItem->Image = $product->RemoteImage;
        $cartItem->IsSelected = TRUE;
		$cartItem->save();
		return $cartItem;
	}
	
	/**
	 * 清空购物车
	 */
	public function clear(){
		Application_Model_CartItem::clearCart($this->Id);
	}
    
    public function createOrders(){
        $shops = $this->getShops();
        $result = array();
        foreach ($shops as $shop){
            $order =new Application_Model_Order();
            $order->DateCreated = date('Y-m-d H:i:s');
            $order->Status = Application_Model_Order::STATUS_PAYING;
            //$order->UserId = Application_Model_User::current()->Id;		
            $productTotal = 0;
            $fees = array();
            foreach ($this->getItemsByShopId($shop->Id) as $item){			
                $orderItem = new Application_Model_OrderItem();
                $orderItem->ProductId = $item->ProductId;
                $orderItem->Price = $item->Price;
                $orderItem->Quantity = $item->Quantity;
                $orderItem->ProductName = $item->ProductName;
                $orderItem->Comment = $item->Comment;
                $order->addItem($orderItem);
                $fees[] = $item->ShipFee;
                $productTotal += $item->SubTotal;
            }
            $order->ShipFee = max($fees);
            $order->Sum = $productTotal + $order->ShipFee;
            $order->productTotal = $productTotal;
            $result[] = $order;
        }
        return $result;
    }
}